#include "hostilerelationspanel.h"
#include "createnodedialog.h"

HostilerelationParamEditPanel::HostilerelationParamEditPanel(wxWindow* parent)
    : wxPanel(parent, wxID_ANY),
      mRouteCondiItem(NULL),
      m_startlightTextEditFinished(false),
      m_endlightTextEditFinished(false),
      m_conflictsignalEditFinished(false),
      m_conflictswitchEditFinished(false),
      m_followswitchEditFinished(false)
{
    InitUI();
}

HostilerelationParamEditPanel::~HostilerelationParamEditPanel()
{

}

// 挂接道岔改变信号槽
void HostilerelationParamEditPanel::sig_ProcessItemChanged(hostilerelationspanel *phostilerelationspanel)
{
    sig_item_change.connect(phostilerelationspanel,&hostilerelationspanel::slot_ProcessItemChanged);
    sig_item_selected.connect(phostilerelationspanel,&hostilerelationspanel::slot_ProcessItemSelected);
}

void HostilerelationParamEditPanel::InitUI()
{
    wxArrayString nodeArray;
    std::map<wxString,WBaseNode*> allnodes = WNodeManager::getSingleton().getAllNodes();
    std::map<wxString,WBaseNode*>::iterator iternode = allnodes.begin();
    for(;iternode != allnodes.end();++iternode)
    {
        if((*iternode).second->getNodeType() == NodeType::NODE_SIGNAL)
            nodeArray.push_back((*iternode).second->getName());
    }

    m_startlightLabel = new wxStaticText(this, wxID_ANY, wxT("开始信号灯:"));
    m_startlightText = new wxComboBox(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize,
                                      nodeArray, wxCB_READONLY);

    m_endlightLabel = new wxStaticText(this, wxID_ANY, wxT("结束信号灯:"));
    m_endlightText = new wxComboBox(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize,
                                    nodeArray, wxCB_READONLY);

    m_conflictsignalLabel = new wxStaticText(this, wxID_ANY, wxT("敌对信号灯:"));
    m_conflictsignalText = new wxTextCtrl(this, wxID_ANY, "",
                                    wxDefaultPosition, wxDefaultSize,
                                    wxTE_READONLY);

    m_conflictswitchLabel = new wxStaticText(this, wxID_ANY, wxT("敌对道岔:"));
    m_conflictswitchText = new wxTextCtrl(this, wxID_ANY, "",
                                    wxDefaultPosition, wxDefaultSize,
                                    wxTE_READONLY);

    m_followswitchLabel = new wxStaticText(this, wxID_ANY, wxT("联动道岔:"));
    m_followswitchText = new wxTextCtrl(this, wxID_ANY, "",
                                          wxDefaultPosition, wxDefaultSize,
                                          wxTE_READONLY);

    // 布局
    wxFlexGridSizer* mainSizer = new wxFlexGridSizer(7, 2, 5, 5);
    mainSizer->AddGrowableCol(1);
    mainSizer->SetFlexibleDirection(wxBOTH);

    mainSizer->Add(m_startlightLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    mainSizer->Add(m_startlightText, 1, wxEXPAND | wxALL, 5);

    mainSizer->Add(m_endlightLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    mainSizer->Add(m_endlightText, 1, wxEXPAND | wxALL, 5);

    mainSizer->Add(m_conflictsignalLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    mainSizer->Add(m_conflictsignalText, 1, wxEXPAND | wxALL, 5);

    mainSizer->Add(m_conflictswitchLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    mainSizer->Add(m_conflictswitchText, 1, wxEXPAND | wxALL, 5);

    mainSizer->Add(m_followswitchLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    mainSizer->Add(m_followswitchText, 1, wxEXPAND | wxALL, 5);

    SetSizerAndFit(mainSizer);

    m_startlightText->Bind(wxEVT_TEXT, &HostilerelationParamEditPanel::OnstartlightTextChanged, this);
    m_startlightText->Bind(wxEVT_KILL_FOCUS, &HostilerelationParamEditPanel::OnstartlightTextKillFocus, this);
    m_startlightText->Bind(wxEVT_TEXT_ENTER, &HostilerelationParamEditPanel::OnstartlightTextEnter, this);

    m_endlightText->Bind(wxEVT_TEXT, &HostilerelationParamEditPanel::OnendlightTextChanged, this);
    m_endlightText->Bind(wxEVT_KILL_FOCUS, &HostilerelationParamEditPanel::OnendlightTextKillFocus, this);
    m_endlightText->Bind(wxEVT_TEXT_ENTER, &HostilerelationParamEditPanel::OnendlightTextEnter, this);

    m_conflictsignalText->Bind(wxEVT_TEXT, &HostilerelationParamEditPanel::OnconflictsignalTextChanged, this);
    m_conflictsignalText->Bind(wxEVT_KILL_FOCUS, &HostilerelationParamEditPanel::OnconflictsignalTextKillFocus, this);
    //m_conflictsignalText->Bind(wxEVT_TEXT_ENTER, &HostilerelationParamEditPanel::OnconflictsignalTextEnter, this);

    m_conflictswitchText->Bind(wxEVT_TEXT, &HostilerelationParamEditPanel::OnconflictswitchTextChanged, this);
    m_conflictswitchText->Bind(wxEVT_KILL_FOCUS, &HostilerelationParamEditPanel::OnconflictswitchTextKillFocus, this);
    //m_conflictswitchText->Bind(wxEVT_TEXT_ENTER, &HostilerelationParamEditPanel::OnconflictswitchTextEnter, this);

    m_followswitchText->Bind(wxEVT_TEXT, &HostilerelationParamEditPanel::OnfollowswitchTextChanged, this);
    m_followswitchText->Bind(wxEVT_KILL_FOCUS, &HostilerelationParamEditPanel::OnfollowswitchTextKillFocus, this);
    //m_followswitchText->Bind(wxEVT_TEXT_ENTER, &HostilerelationParamEditPanel::OnfollowswitchTextEnter, this);

    m_conflictsignalText->Bind(wxEVT_SET_FOCUS, &HostilerelationParamEditPanel::OnconflictsignalTextSetFocus, this);
    m_conflictswitchText->Bind(wxEVT_SET_FOCUS, &HostilerelationParamEditPanel::OnconflictswitchTextSetFocus, this);
    m_followswitchText->Bind(wxEVT_SET_FOCUS, &HostilerelationParamEditPanel::OnfollowswitchTextSetFocus, this);
}

void HostilerelationParamEditPanel::OnconflictsignalTextSetFocus(wxFocusEvent& event)
{
    sig_item_selected.emitt(mRouteCondiItem,0);
    event.Skip();
}

void HostilerelationParamEditPanel::OnconflictswitchTextSetFocus(wxFocusEvent& event)
{
    sig_item_selected.emitt(mRouteCondiItem,1);
    event.Skip();
}

void HostilerelationParamEditPanel::OnfollowswitchTextSetFocus(wxFocusEvent& event)
{
    sig_item_selected.emitt(mRouteCondiItem,2);
    event.Skip();
}

void HostilerelationParamEditPanel::OnstartlightTextChanged(wxCommandEvent& event)
{
    m_startlightTextEditFinished = true;
}

void HostilerelationParamEditPanel::OnstartlightTextKillFocus(wxFocusEvent& event)
{
    if(m_startlightTextEditFinished)
    {
        sig_item_change.emitt(mRouteCondiItem,0,m_lastChangedData["startlight"],m_startlightText->GetValue());
        m_lastChangedData["startlight"]=m_startlightText->GetValue();
        m_startlightTextEditFinished = false;
    }
    event.Skip();
}

void HostilerelationParamEditPanel::OnstartlightTextEnter(wxCommandEvent& event)
{
    if(m_startlightTextEditFinished)
    {
        sig_item_change.emitt(mRouteCondiItem,0,m_lastChangedData["startlight"],m_endlightText->GetValue());
        m_lastChangedData["startlight"]=m_endlightText->GetValue();
        m_startlightTextEditFinished = false;
    }
    event.Skip();
}

void HostilerelationParamEditPanel::OnendlightTextChanged(wxCommandEvent& event)
{
    m_endlightTextEditFinished = true;
}

void HostilerelationParamEditPanel::OnendlightTextKillFocus(wxFocusEvent& event)
{
    if(m_endlightTextEditFinished)
    {
        sig_item_change.emitt(mRouteCondiItem,1,m_lastChangedData["endlight"],m_startlightText->GetValue());
        m_lastChangedData["endlight"]=m_startlightText->GetValue();
        m_endlightTextEditFinished = false;
    }
    event.Skip();
}

void HostilerelationParamEditPanel::OnendlightTextEnter(wxCommandEvent& event)
{
    if(m_endlightTextEditFinished)
    {
        sig_item_change.emitt(mRouteCondiItem,1,m_lastChangedData["endlight"],m_startlightText->GetValue());
        m_lastChangedData["endlight"]=m_startlightText->GetValue();
        m_endlightTextEditFinished = false;
    }
    event.Skip();
}

void HostilerelationParamEditPanel::OnconflictsignalTextChanged(wxCommandEvent& event)
{
    m_conflictsignalEditFinished = true;
}

void HostilerelationParamEditPanel::OnconflictsignalTextKillFocus(wxFocusEvent& event)
{
    if(m_conflictsignalEditFinished)
    {
        sig_item_change.emitt(mRouteCondiItem,2,m_lastChangedData["conflictsignal"],m_conflictsignalText->GetValue());
        m_lastChangedData["conflictsignal"]=m_conflictsignalText->GetValue();
        m_conflictsignalEditFinished = false;
    }
    event.Skip();
}

void HostilerelationParamEditPanel::OnconflictsignalTextEnter(wxCommandEvent& event)
{
    if(m_conflictsignalEditFinished)
    {
        sig_item_change.emitt(mRouteCondiItem,2,m_lastChangedData["conflictsignal"],m_conflictsignalText->GetValue());
        m_lastChangedData["conflictsignal"]=m_conflictsignalText->GetValue();
        m_conflictsignalEditFinished = false;
    }
    event.Skip();
}

void HostilerelationParamEditPanel::OnconflictswitchTextChanged(wxCommandEvent& event)
{
    m_conflictswitchEditFinished = true;
}

void HostilerelationParamEditPanel::OnconflictswitchTextKillFocus(wxFocusEvent& event)
{
    if(m_conflictswitchEditFinished)
    {
        sig_item_change.emitt(mRouteCondiItem,3,m_lastChangedData["conflictswitch"],m_conflictswitchText->GetValue());
        m_lastChangedData["conflictswitch"]=m_conflictswitchText->GetValue();
        m_conflictswitchEditFinished = false;
    }
    event.Skip();
}

void HostilerelationParamEditPanel::OnconflictswitchTextEnter(wxCommandEvent& event)
{
    if(m_conflictswitchEditFinished)
    {
        sig_item_change.emitt(mRouteCondiItem,3,m_lastChangedData["conflictswitch"],m_conflictswitchText->GetValue());
        m_lastChangedData["conflictswitch"]=m_conflictswitchText->GetValue();
        m_conflictswitchEditFinished = false;
    }
    event.Skip();
}

void HostilerelationParamEditPanel::OnfollowswitchTextChanged(wxCommandEvent& event)
{
    m_followswitchEditFinished = true;
}

void HostilerelationParamEditPanel::OnfollowswitchTextKillFocus(wxFocusEvent& event)
{
    if(m_followswitchEditFinished)
    {
        sig_item_change.emitt(mRouteCondiItem,4,m_lastChangedData["followswitch"],m_followswitchText->GetValue());
        m_lastChangedData["followswitch"]=m_followswitchText->GetValue();
        m_followswitchEditFinished = false;
    }
    event.Skip();
}

void HostilerelationParamEditPanel::OnfollowswitchTextEnter(wxCommandEvent& event)
{
    if(m_followswitchEditFinished)
    {
        sig_item_change.emitt(mRouteCondiItem,4,m_lastChangedData["followswitch"],m_followswitchText->GetValue());
        m_lastChangedData["followswitch"]=m_followswitchText->GetValue();
        m_followswitchEditFinished = false;
    }
    event.Skip();
}

// 重置所有参数
void HostilerelationParamEditPanel::resetAllData(void)
{
    m_startlightText->Clear();
    m_endlightText->Clear();

    //wxArrayString nodeArray;
    std::map<wxString,WBaseNode*> allnodes = WNodeManager::getSingleton().getAllNodes();
    std::map<wxString,WBaseNode*>::iterator iternode = allnodes.begin();
    for(;iternode != allnodes.end();++iternode)
    {
        if((*iternode).second->getNodeType() == NodeType::NODE_SIGNAL)
        {
            //nodeArray.push_back((*iternode).second->getName());

            m_startlightText->Append((*iternode).second->getName());
            m_endlightText->Append((*iternode).second->getName());
        }
    }

    m_conflictsignalText->SetValue("");
    m_conflictswitchText->SetValue("");
    m_followswitchText->SetValue("");
}

// 获取所有参数数据
std::map<wxString, wxString> HostilerelationParamEditPanel::GetData() const
{
    std::map<wxString, wxString> data;
    data["startlight"] = m_startlightText->GetValue();
    data["endlight"] = m_endlightText->GetValue();
    data["conflictsignal"] = m_conflictsignalText->GetValue();
    data["conflictswitch"] = m_conflictswitchText->GetValue();
    data["followswitch"] = m_followswitchText->GetValue();

    return data;
}

// 设置参数数据
void HostilerelationParamEditPanel::SetData(const std::map<wxString, wxString>& data)
{
    m_lastChangedData = data;

    if (data.count("startlight")) m_startlightText->SetValue(data.at("startlight"));
    if (data.count("endlight")) m_endlightText->SetValue(data.at("endlight"));
    if (data.count("conflictsignal")) m_conflictsignalText->SetValue(data.at("conflictsignal"));
    if (data.count("conflictswitch")) m_conflictswitchText->SetValue(data.at("conflictswitch"));
    if (data.count("followswitch")) m_followswitchText->SetValue(data.at("followswitch"));
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

HostilerelationParamPanel::HostilerelationParamPanel(wxWindow *parent)
    : wxPanel(parent),
      mRouteCondiItem(NULL),
      m_curSelecteditemindex(-1)
{
    // 创建主垂直布局
    wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL);

    // 创建DataViewCtrl
    m_dvc = new wxDataViewCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxDV_MULTIPLE);

    // 创建数据存储
    m_store = new wxDataViewListStore();
    m_dvc->AssociateModel(m_store);

    mainSizer->Add(m_dvc, 1, wxEXPAND);

    SetSizer(mainSizer);

    this->Bind(wxEVT_DATAVIEW_ITEM_EDITING_DONE, &HostilerelationParamPanel::OnEditingDone, this, m_dvc->GetId());
    m_dvc->Bind(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, &HostilerelationParamPanel::OnRightClick, this);
}

HostilerelationParamPanel::~HostilerelationParamPanel()
{

}

// 挂接道岔改变信号槽
void HostilerelationParamPanel::sig_ProcessRangeItemChanged(hostilerelationspanel *phostilerelationspanel)
{
    sig_range_change.connect(phostilerelationspanel,&hostilerelationspanel::slot_ProcessItemRangeChanged);
    sig_add_del_change.connect(phostilerelationspanel,&hostilerelationspanel::slot_ProcessItemAddAndDelete);
}

// 重置所有参数
void HostilerelationParamPanel::resetAllData(void)
{
    m_store->DeleteAllItems();
    m_dvc->ClearColumns();
}

void HostilerelationParamPanel::initAllItem(int itemIndex)
{
    m_curSelecteditemindex = itemIndex;
    this->resetAllData();

    switch(itemIndex)
    {
    case 0:
    {
        wxArrayString nodeArray;
        std::map<wxString,WBaseNode*> allnodes = WNodeManager::getSingleton().getAllNodes();
        std::map<wxString,WBaseNode*>::iterator iternode = allnodes.begin();
        for(;iternode != allnodes.end();++iternode)
        {
            if((*iternode).second->getNodeType() == NodeType::NODE_SIGNAL)
                nodeArray.push_back((*iternode).second->getName());
        }

        wxDataViewColumn *choicescolumn = new wxDataViewColumn(
            "敌对信号灯",
            new wxDataViewChoiceRenderer(nodeArray, wxDATAVIEW_CELL_EDITABLE, wxALIGN_LEFT),
            0,
            100);
        m_dvc->AppendColumn(choicescolumn);
    }
        break;
    case 1:
    case 2:
    {
        wxArrayString nodeArray;
        std::map<wxString,WBaseNode*> allnodes = WNodeManager::getSingleton().getAllNodes();
        std::map<wxString,WBaseNode*>::iterator iternode = allnodes.begin();
        for(;iternode != allnodes.end();++iternode)
        {
            if((*iternode).second->getNodeType() == NodeType::NODE_SWITCH)
                nodeArray.push_back((*iternode).second->getName());
        }

        wxDataViewColumn *choicescolumn = new wxDataViewColumn(
            itemIndex == 1 ? wxT("敌对道岔") : wxT("联动道岔"),
            new wxDataViewChoiceRenderer(nodeArray, wxDATAVIEW_CELL_EDITABLE, wxALIGN_LEFT),
            0,
            80);
        m_dvc->AppendColumn(choicescolumn);

        wxArrayString choices;
        choices.Add(wxT("定位"));
        choices.Add(wxT("反位"));

        wxDataViewColumn* column = new wxDataViewColumn(
            wxT("道岔状态"),
            new wxDataViewChoiceRenderer(choices, wxDATAVIEW_CELL_EDITABLE, wxALIGN_LEFT),
            1,
            80);
        m_dvc->AppendColumn(column);
    }
        break;
    defaut:
        break;
    }
}

void HostilerelationParamPanel::OnRightClick(wxDataViewEvent& event)
{
    if(mRouteCondiItem == NULL)
        return;

    wxDataViewItem item = event.GetItem();
    if (item.IsOk())
    {
        wxVariant decvalue;
        m_dvc->GetModel()->GetValue(decvalue, item, 0);

        // 创建并显示菜单
        wxMenu menu;
        switch(m_curSelecteditemindex)
        {
        case 0: menu.Append(IDD_PARAMEDIT_DELETENODE,
                        wxString::Format(wxT("删除敌对信号灯 '%s'"),decvalue.GetString())); break;
        case 1: menu.Append(IDD_PARAMEDIT_DELETENODE,
                        wxString::Format(wxT("删除敌对道岔 '%s'"),decvalue.GetString())); break;
        case 2: menu.Append(IDD_PARAMEDIT_DELETENODE,
                        wxString::Format(wxT("删除联动道岔 '%s'"),decvalue.GetString())); break;
        }
        menu.Bind(wxEVT_MENU, &HostilerelationParamPanel::OnDeleteRange, this, IDD_PARAMEDIT_DELETENODE);

        m_dvc->PopupMenu(&menu, event.GetPosition());
    }
    else
    {
        // 创建并显示菜单
        wxMenu menu;

        switch(m_curSelecteditemindex)
        {
        case 0: menu.Append(IDD_PARAMEDIT_ADD_MOUNTNODE,wxT("添加敌对信号灯")); break;
        case 1: menu.Append(IDD_PARAMEDIT_ADD_MOUNTNODE,wxT("添加敌对道岔")); break;
        case 2: menu.Append(IDD_PARAMEDIT_ADD_MOUNTNODE,wxT("添加联动道岔")); break;
        default: break;
        }

        menu.Bind(wxEVT_MENU, &HostilerelationParamPanel::OnAddNewRange, this, IDD_PARAMEDIT_ADD_MOUNTNODE);

        m_dvc->PopupMenu(&menu, event.GetPosition());
    }

    event.Skip();
}

void HostilerelationParamPanel::OnDeleteRange(wxCommandEvent& event)
{
    wxString tipStr;
    switch(m_curSelecteditemindex)
    {
    case 0: tipStr = wxT("您是否要删除当前敌对信号灯?"); break;
    case 1: tipStr = wxT("您是否要删除当前敌对道岔?"); break;
    case 2: tipStr = wxT("您是否要删除当前联动道岔?"); break;
    }

    wxMessageDialog dialog(
        this,
        tipStr,
        wxT("警告"),
        wxYES_NO | wxICON_QUESTION | wxICON_WARNING
        );

    if (dialog.ShowModal() == wxID_YES && mRouteCondiItem != NULL)
    {
        wxVariant decvalue;
        m_dvc->GetModel()->GetValue(decvalue, m_dvc->GetSelection(), 0);

        switch(m_curSelecteditemindex)
        {
        case 0:
        {
            if(mRouteCondiItem)
                mRouteCondiItem->removeconflictsignals(decvalue.GetString());
        }
            break;
        case 1:
        {
            if(mRouteCondiItem)
                mRouteCondiItem->removeconflictswitch(decvalue.GetString());
        }
            break;
        case 2:
        {
            if(mRouteCondiItem)
                mRouteCondiItem->removefollowswitch(decvalue.GetString());
        }
            break;
        default:
            break;
        }

        sig_add_del_change.emitt(1000+m_curSelecteditemindex,mRouteCondiItem);

        m_store->DeleteItem(m_store->GetRow(m_dvc->GetSelection()));
    }
}

void HostilerelationParamPanel::OnAddNewRange(wxCommandEvent& event)
{
    if(mRouteCondiItem == NULL)
        return;

    switch(m_curSelecteditemindex)
    {
    case 0:
    {
        CreateNodeDialog dlg(this, wxT("创建敌对信号灯"));
        if (dlg.ShowModal() == wxID_OK)
        {
            wxString nodeName = dlg.GetNodeName();

            if(mRouteCondiItem->getconflictsignals(nodeName) == NULL)
            {
                WBaseNode *pBaseNode = WNodeManager::getSingleton().getNodeByName(nodeName);
                if(pBaseNode != NULL && pBaseNode->getNodeType() == NodeType::NODE_SIGNAL)
                {
                    mRouteCondiItem->conflictsignals.push_back(static_cast<WSignalLampNode*>(pBaseNode));

                    wxVector<wxVariant> decdata;
                    decdata.push_back(nodeName);

                    this->addData(decdata);

                    sig_add_del_change.emitt(2000+m_curSelecteditemindex,mRouteCondiItem);
                }
            }
        }
    }
    break;
    case 1:
    {
        CreateNodeDialog dlg(this, wxT("创建敌对道岔"));
        if (dlg.ShowModal() == wxID_OK)
        {
            wxString nodeName = dlg.GetNodeName();

            if(mRouteCondiItem->getconflictswitch(nodeName) == NULL)
            {
                WBaseNode *pBaseNode = WNodeManager::getSingleton().getNodeByName(nodeName);
                if(pBaseNode != NULL && pBaseNode->getNodeType() == NodeType::NODE_SWITCH)
                {
                    mRouteCondiItem->conflictswitch.push_back(tagSwitchCondiItem(static_cast<WSwitchNode*>(pBaseNode),SwitchState::POSITIVE));

                    wxVector<wxVariant> decdata;
                    decdata.push_back(nodeName);
                    decdata.push_back(wxT("定位"));

                    this->addData(decdata);

                    sig_add_del_change.emitt(2000+m_curSelecteditemindex,mRouteCondiItem);
                }
            }
        }
    }
    break;
    case 2:
    {
        CreateNodeDialog dlg(this, wxT("创建联动道岔"));
        if (dlg.ShowModal() == wxID_OK)
        {
            wxString nodeName = dlg.GetNodeName();

            if(mRouteCondiItem->getfollowswitch(nodeName) == NULL)
            {
                WBaseNode *pBaseNode = WNodeManager::getSingleton().getNodeByName(nodeName);
                if(pBaseNode != NULL && pBaseNode->getNodeType() == NodeType::NODE_SWITCH)
                {
                    mRouteCondiItem->followswitch.push_back(tagSwitchCondiItem(static_cast<WSwitchNode*>(pBaseNode),SwitchState::POSITIVE));

                    wxVector<wxVariant> decdata;
                    decdata.push_back(nodeName);
                    decdata.push_back(wxT("定位"));

                    this->addData(decdata);

                    sig_add_del_change.emitt(2000+m_curSelecteditemindex,mRouteCondiItem);
                }
            }
        }
    }
    break;
    default:
        break;
    }
}

void HostilerelationParamPanel::OnEditingDone(wxDataViewEvent& event)
{
    event.Skip();

    wxDataViewItem item = event.GetItem();
    int col = event.GetColumn();

    if (event.IsEditCancelled())
        return;

    wxVariant oldvalue;
    m_dvc->GetModel()->GetValue(oldvalue, item, col);
    wxVariant newvalue = event.GetValue();

    if(oldvalue.GetString() == newvalue.GetString() ||
        newvalue.GetString() == "" ||
        mRouteCondiItem == NULL)
        return;

    if(m_curSelecteditemindex == 1 || m_curSelecteditemindex == 2)
    {
        if(col == 0)
        {
            if(m_curSelecteditemindex == 1)
            {
                mRouteCondiItem->removeconflictswitch(oldvalue.GetString());

                WBaseNode *pBaseNode = WNodeManager::getSingleton().getNodeByName(newvalue.GetString());
                if(pBaseNode != NULL && pBaseNode->getNodeType() == NodeType::NODE_SWITCH)
                {
                    mRouteCondiItem->conflictswitch.push_back(tagSwitchCondiItem(static_cast<WSwitchNode*>(pBaseNode),SwitchState::POSITIVE));

                    sig_add_del_change.emitt(2000+m_curSelecteditemindex,mRouteCondiItem);
                }
            }
            else
            {
                mRouteCondiItem->removefollowswitch(oldvalue.GetString());

                WBaseNode *pBaseNode = WNodeManager::getSingleton().getNodeByName(newvalue.GetString());
                if(pBaseNode != NULL && pBaseNode->getNodeType() == NodeType::NODE_SWITCH)
                {
                    mRouteCondiItem->followswitch.push_back(tagSwitchCondiItem(static_cast<WSwitchNode*>(pBaseNode),SwitchState::POSITIVE));

                    sig_add_del_change.emitt(2000+m_curSelecteditemindex,mRouteCondiItem);
                }
            }
        }
        else if(col == 1)
        {
            wxVariant itemvalue;
            m_dvc->GetModel()->GetValue(itemvalue, item, 0);

            if(m_curSelecteditemindex == 1)
            {
                for(int i=0;i<mRouteCondiItem->conflictswitch.size();i++)
                {
                    if(mRouteCondiItem->conflictswitch[i].switchnode->getName() == itemvalue.GetString())
                    {
                        mRouteCondiItem->conflictswitch[i].switchstate = (newvalue.GetString() == wxT("定位") ? SwitchState::POSITIVE : SwitchState::NEGATIVE);
                        sig_add_del_change.emitt(2000+m_curSelecteditemindex,mRouteCondiItem);
                        break;
                    }
                }
            }
            else
            {
                for(int i=0;i<mRouteCondiItem->followswitch.size();i++)
                {
                    if(mRouteCondiItem->followswitch[i].switchnode->getName() == itemvalue.GetString())
                    {
                        mRouteCondiItem->followswitch[i].switchstate = (newvalue.GetString() == wxT("定位") ? SwitchState::POSITIVE : SwitchState::NEGATIVE);
                        sig_add_del_change.emitt(2000+m_curSelecteditemindex,mRouteCondiItem);
                        break;
                    }
                }
            }
        }
    }
    else if(m_curSelecteditemindex == 0 && col == 0)
    {
        mRouteCondiItem->removeconflictsignals(oldvalue.GetString());

        WBaseNode *pBaseNode = WNodeManager::getSingleton().getNodeByName(newvalue.GetString());
        if(pBaseNode != NULL && pBaseNode->getNodeType() == NodeType::NODE_SIGNAL)
        {
            mRouteCondiItem->conflictsignals.push_back(static_cast<WSignalLampNode*>(pBaseNode));

            sig_add_del_change.emitt(2000+m_curSelecteditemindex,mRouteCondiItem);
        }
    }
}

void HostilerelationParamPanel::clearAllData(void)
{
    m_store->DeleteAllItems();
}

// 重新加载所有的结点
void HostilerelationParamPanel::reloadAllNodes(void)
{
    m_dvc->Refresh();
}

void HostilerelationParamPanel::addData(const wxVector<wxVariant> data)
{
    m_store->AppendItem(data);
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

hostilerelationspanel::hostilerelationspanel(wxWindow *parent)
    : wxPanel(parent),
    m_curSelecteditemindex(-1)
{
    // 创建主垂直布局
    wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL);
    wxBoxSizer* panelSizer = new wxBoxSizer(wxHORIZONTAL);
    wxBoxSizer* mountSizer = new wxBoxSizer(wxVERTICAL);

    m_HostilerelationParamEditPanel = new HostilerelationParamEditPanel(this);
    m_HostilerelationParamPanel = new HostilerelationParamPanel(this);

    m_HostilerelationParamEditPanel->sig_ProcessItemChanged(this);
    m_HostilerelationParamPanel->sig_ProcessRangeItemChanged(this);

    // 创建DataViewCtrl
    m_dvc = new wxDataViewCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxDV_MULTIPLE);

    // 创建数据存储
    m_store = new wxDataViewListStore();
    m_dvc->AssociateModel(m_store);

    mountSizer->Add(m_HostilerelationParamEditPanel, 1, wxEXPAND);
    mountSizer->Add(m_HostilerelationParamPanel, 1, wxEXPAND);

    panelSizer->Add(m_dvc, 3, wxEXPAND);
    panelSizer->Add(mountSizer, 1, wxEXPAND);

    mainSizer->Add(panelSizer, 1, wxEXPAND);

    SetSizer(mainSizer);

    m_dvc->AppendTextColumn(wxT("开始信号灯"), m_dvc->GetColumnCount(), wxDATAVIEW_CELL_ACTIVATABLE, 100);
    m_dvc->AppendTextColumn(wxT("结束信号灯"), m_dvc->GetColumnCount(), wxDATAVIEW_CELL_ACTIVATABLE, 100);
    m_dvc->AppendTextColumn(wxT("敌对信号灯"), m_dvc->GetColumnCount(), wxDATAVIEW_CELL_ACTIVATABLE, 180);
    m_dvc->AppendTextColumn(wxT("敌对道岔"), m_dvc->GetColumnCount(), wxDATAVIEW_CELL_ACTIVATABLE, 180);
    m_dvc->AppendTextColumn(wxT("联动道岔"), m_dvc->GetColumnCount(), wxDATAVIEW_CELL_ACTIVATABLE, 180);

    m_dvc->Bind(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, &hostilerelationspanel::OnRightClick, this);
    m_dvc->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, &hostilerelationspanel::OnSelectionChanged, this);
}

hostilerelationspanel::~hostilerelationspanel()
{

}

void hostilerelationspanel::slot_ProcessItemAddAndDelete(int operType,tagRouteCondiItem *pRouteCondiItem)
{
    if(operType < 0 || pRouteCondiItem == NULL)
        return;

    switch(operType < 2000 ? operType-1000 : operType-2000)
    {
    case 0:
    {
        wxString conflictsignalsStr;
        for(int i=0;i<pRouteCondiItem->conflictsignals.size();i++)
            conflictsignalsStr += wxString::Format(wxT("%s;"),pRouteCondiItem->conflictsignals[i]->getName());
        conflictsignalsStr = conflictsignalsStr.empty() ? "" : conflictsignalsStr.Mid(0,conflictsignalsStr.length()-1);

        m_HostilerelationParamEditPanel->setconflictsignal(conflictsignalsStr);

        wxDataViewItem selected = m_dvc->GetSelection();

        if (selected.IsOk())
        {
            const wxDataViewColumn* column = m_dvc->GetColumn(2);

            m_store->SetValue(wxVariant(conflictsignalsStr), selected, column->GetModelColumn());
            m_store->ItemChanged(selected);
        }
    }
    break;
    case 1:
    {
        wxString conflictswitchStr;
        for(int i=0;i<pRouteCondiItem->conflictswitch.size();i++)
            conflictswitchStr += wxString::Format(wxT("%s:%s;"),
                                                  pRouteCondiItem->conflictswitch[i].switchnode->getName(),
                                                  pRouteCondiItem->conflictswitch[i].switchstate == SwitchState::POSITIVE ? wxT("定位") : wxT("反位"));
        conflictswitchStr = conflictswitchStr.empty() ? "" : conflictswitchStr.Mid(0,conflictswitchStr.length()-1);

        m_HostilerelationParamEditPanel->setconflictswitch(conflictswitchStr);

        wxDataViewItem selected = m_dvc->GetSelection();

        if (selected.IsOk())
        {
            const wxDataViewColumn* column = m_dvc->GetColumn(3);

            m_store->SetValue(wxVariant(conflictswitchStr), selected, column->GetModelColumn());
            m_store->ItemChanged(selected);
        }
    }
    break;
    case 2:
    {
        wxString followswitchStr;
        for(int i=0;i<pRouteCondiItem->followswitch.size();i++)
            followswitchStr += wxString::Format(wxT("%s:%s;"),
                                                pRouteCondiItem->followswitch[i].switchnode->getName(),
                                                pRouteCondiItem->followswitch[i].switchstate == SwitchState::POSITIVE ? wxT("定位") : wxT("反位"));
        followswitchStr = followswitchStr.empty() ? "" : followswitchStr.Mid(0,followswitchStr.length()-1);

        m_HostilerelationParamEditPanel->setfollowswitch(followswitchStr);

        wxDataViewItem selected = m_dvc->GetSelection();

        if (selected.IsOk())
        {
            const wxDataViewColumn* column = m_dvc->GetColumn(4);

            m_store->SetValue(wxVariant(followswitchStr), selected, column->GetModelColumn());
            m_store->ItemChanged(selected);
        }
    }
    break;
    default:
        break;
    }
}

void hostilerelationspanel::slot_ProcessItemSelected(tagRouteCondiItem *pRouteCondiItem,int itemindex)
{
    if(pRouteCondiItem == NULL) return;

    m_curSelecteditemindex = itemindex;
    m_HostilerelationParamPanel->initAllItem(itemindex);

    switch(m_curSelecteditemindex)
    {
    case 0:
    {
        for(int i=0;i<pRouteCondiItem->conflictsignals.size();i++)
        {
            wxVector<wxVariant> decdata;
            decdata.push_back(pRouteCondiItem->conflictsignals[i]->getName());

            m_HostilerelationParamPanel->addData(decdata);
        }
    }
        break;
    case 1:
    {
        for(int i=0;i<pRouteCondiItem->conflictswitch.size();i++)
        {
            wxVector<wxVariant> decdata;
            decdata.push_back(pRouteCondiItem->conflictswitch[i].switchnode->getName());
            decdata.push_back(pRouteCondiItem->conflictswitch[i].switchstate == SwitchState::POSITIVE ? wxT("定位") : wxT("反位"));

            m_HostilerelationParamPanel->addData(decdata);
        }
    }
        break;
    case 2:
    {
        for(int i=0;i<pRouteCondiItem->followswitch.size();i++)
        {
            wxVector<wxVariant> decdata;
            decdata.push_back(pRouteCondiItem->followswitch[i].switchnode->getName());
            decdata.push_back(pRouteCondiItem->followswitch[i].switchstate == SwitchState::POSITIVE ? wxT("定位") : wxT("反位"));

            m_HostilerelationParamPanel->addData(decdata);
        }
    }
        break;
    default:
        break;
    }
}

void hostilerelationspanel::slot_ProcessItemChanged(tagRouteCondiItem *pRouteCondiItem,int itemindex,wxString olddata,wxString newdata)
{

}

void hostilerelationspanel::slot_ProcessItemRangeChanged(wxString oldparams,wxString newparams)
{

}

void hostilerelationspanel::OnSelectionChanged(wxDataViewEvent& event)
{
    // 获取当前选中的项目
    wxDataViewItem selectedItem = m_dvc->GetSelection();

    if (selectedItem.IsOk())
    {
        // 获取模型
        wxDataViewModel* model = m_dvc->GetModel();

        m_HostilerelationParamEditPanel->resetAllData();
        m_HostilerelationParamPanel->resetAllData();

        std::map<wxString, wxString> data;

        // 获取第一列的值
        wxVariant value;
        model->GetValue(value, selectedItem, 0);
        data["startlight"] = value.GetString();
        model->GetValue(value, selectedItem, 1);
        data["endlight"] = value.GetString();
        model->GetValue(value, selectedItem, 2);
        data["conflictsignal"] = value.GetString();
        model->GetValue(value, selectedItem, 3);
        data["conflictswitch"] = value.GetString();
        model->GetValue(value, selectedItem, 4);
        data["followswitch"] = value.GetString();

        m_HostilerelationParamEditPanel->SetData(data);

        tagRouteCondiItem *pRouteCondiItem = CRouteConditions::getSingleton().getRouteCondiItem(data["startlight"],data["endlight"]);
        if(pRouteCondiItem != NULL)
        {
            m_HostilerelationParamEditPanel->setRouteCondiItem(pRouteCondiItem);
            m_HostilerelationParamPanel->setRouteCondiItem(pRouteCondiItem);
        }
    }
}

void hostilerelationspanel::OnRightClick(wxDataViewEvent& event)
{
    wxDataViewItem item = event.GetItem();
    if (item.IsOk())
    {
        // 获取第一列的值
        wxVariant value;
        m_dvc->GetModel()->GetValue(value, item, 0);

        // 创建并显示菜单
        wxMenu menu;
        menu.Append(IDD_PARAMEDIT_DELETENODE,
                    wxString::Format(wxT("删除 '%s'"),value.GetString()));
        menu.Bind(wxEVT_MENU, &hostilerelationspanel::OnDeleteSect, this, IDD_PARAMEDIT_DELETENODE);

        m_dvc->PopupMenu(&menu, event.GetPosition());
    }
    else
    {
        // 创建并显示菜单
        wxMenu menu;
        menu.Append(IDD_PARAMEDIT_ADD_MOUNTNODE,wxT("添加敌对关系"));

        menu.Bind(wxEVT_MENU, &hostilerelationspanel::OnAddNewSect, this, IDD_PARAMEDIT_ADD_MOUNTNODE);

        m_dvc->PopupMenu(&menu, event.GetPosition());
    }

    event.Skip();
}

void hostilerelationspanel::addRouteCondiItem(tagRouteCondiItem* routecondi)
{
    if(routecondi == NULL) return;

    wxVector<wxVariant> decdata;
    decdata.push_back(routecondi->startLight);
    decdata.push_back(routecondi->endLight);

    wxString conflictsignalsStr;
    for(int i=0;i<routecondi->conflictsignals.size();i++)
        conflictsignalsStr += wxString::Format(wxT("%s;"),routecondi->conflictsignals[i]->getName());
    decdata.push_back(conflictsignalsStr.empty() ? "" : conflictsignalsStr.Mid(0,conflictsignalsStr.length()-1));

    wxString conflictswitchStr;
    for(int i=0;i<routecondi->conflictswitch.size();i++)
        conflictswitchStr += wxString::Format(wxT("%s:%s;"),
                                              routecondi->conflictswitch[i].switchnode->getName(),
                                              routecondi->conflictswitch[i].switchstate == SwitchState::POSITIVE ? wxT("定位") : wxT("反位"));
    decdata.push_back(conflictswitchStr.empty() ? "" : conflictswitchStr.Mid(0,conflictswitchStr.length()-1));

    wxString followswitchStr;
    for(int i=0;i<routecondi->followswitch.size();i++)
        followswitchStr += wxString::Format(wxT("%s:%s;"),
                                         routecondi->followswitch[i].switchnode->getName(),
                                            routecondi->followswitch[i].switchstate == SwitchState::POSITIVE ? wxT("定位") : wxT("反位"));
    decdata.push_back(followswitchStr.empty() ? "" : followswitchStr.Mid(0,followswitchStr.length()-1));

    this->addData(decdata);
}

void hostilerelationspanel::addData(const wxVector<wxVariant> data)
{
    m_store->AppendItem(data);
}

void hostilerelationspanel::OnDeleteSect(wxCommandEvent& event)
{

}

void hostilerelationspanel::OnAddNewSect(wxCommandEvent& event)
{
    CreateRouteConditionDialog dlg(this, wxT("创建敌对关系"));
    if (dlg.ShowModal() == wxID_OK)
    {
        tagRouteCondiItem pRouteCondiItem;
        pRouteCondiItem.startLight = dlg.GetStartLight();
        pRouteCondiItem.endLight = dlg.GetEndLight();

        if(CRouteConditions::getSingleton().addRouteCondiItem(pRouteCondiItem))
        {
            this->addRouteCondiItem(CRouteConditions::getSingleton().getRouteCondiItem(pRouteCondiItem.startLight,
                                                                                       pRouteCondiItem.endLight));
        }
    }
}
